<template>
  <div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('GroupOpenBtn') > -1" class="doumee_table_header">
      <el-button
        v-if="meta.indexOf('GroupOpenBtn') > -1"
        v-preventReClick
        type="primary"
        @click="memberOpen"
      >{{ $t('message.tthykt') }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        :label="$t('message.ttmc')"
        min-width="200"
        prop="teamName"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span class="primaryColor pointer" @click="groupDetail(scope.row.teamId)">
            {{ scope.row.teamName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.gly')"
        prop="admin"
        min-width="140"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.tyrs')"
        prop="count"
        min-width="80"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.tthykklx')"
        prop="cardType"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.ljqyje')"
        prop="amot"
        show-overflow-tooltip
        min-width="120"
      />
      <el-table-column
        align="center"
        :label="$t('message.zhye')"
        prop="zhye"
        show-overflow-tooltip
        min-width="120"
      />
      <el-table-column
        align="center"
        :label="$t('message.createTime')"
        prop="createDate"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column :label="$t('message.caozuo')" :width="$i18n.locale === 'ZH'? 220 : 350" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-preventReClick
              type="text"
              @click="editGroup(scope.row.teamId)"
            >{{ $t('message.edit') }}</el-button>
            <el-button
              v-preventReClick
              type="text"
              @click="ShowManaMem(scope.row)"
            >{{ $t('message.glty') }}</el-button>
            <el-popover
              :key="`popover-${scope.row.teamId}`"
              placement="bottom"
              width="120"
              class="el-pop-btns"
              trigger="hover"
            >
              <div>
                <div
                  v-preventReClick
                  class="moreBtn"
                  @click="backOut(scope.row.teamId)"
                >{{ $t('message.chexiao') }}</div>
                <!-- <div
                  v-preventReClick
                  class="moreBtn"
                  @click="reNew(scope.row.teamId)"
                >{{ $t('message.xuqian') }}</div> -->
                <div
                  v-preventReClick
                  class="moreBtn"
                  @click="changeAdmintor(scope.row)"
                >{{ $t('message.ghgly') }}</div>
              </div>
              <el-button slot="reference" type="text" class="moreBtnShow">{{ $t('message.more') }}<i class="el-icon-caret-bottom primaryColor" /></el-button>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog :title="$t('message.ghgly')" :visible.sync="showDetails" :before-close="cancelChangeAdmin" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <div class="warnningTip">{{ $t('message.ghglysm') }}</div>
      <el-form
        ref="ruleForm"
        class="doumee-form"
        :model="form"
        label-width="auto"
        label-suffix="："
      >
        <el-form-item :label="$t('message.ygly')">
          <el-input
            v-model="form.admin"
            disabled
            type="text"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('message.xgly')">
          <el-input
            v-model="cardNum"
            :placeholder="$t('message.qsr') + $t('message.hy1')"
            class="input-with-select bottom-speace-style"
            @keyup.enter.native="searchAction"
          >
            <el-button slot="append" icon="el-icon-search" @click="searchAction" />
          </el-input>
          <div v-if="showMessage" class="card-message">
            <div class="first-line">
              <span class="message-title-style">NO.</span>
              <span class="message-value-style">{{ cardMessage.number }}</span>
              <span class="message-value-style">{{ cardMessage.nickName }}</span>
              <span v-if="cardMessage.cardName" class="card-name-style">{{ cardMessage.cardName }}</span>
              <button class="message-title-style close-style" @click="closeMessage">x</button>
            </div>
            <div class="first-line">
              <span class="message-title-style">{{ $t('message.sj') }}：</span>
              <span class="message-value-style">{{ cardMessage.phone }}</span>
              <span class="message-title-style">{{ $t('message.czje') }}：</span>
              <span class="message-value-style">{{ cardMessage.remainingMoney?cardMessage.remainingMoney:0 }}</span>
              <span class="message-title-style">{{ $t('message.zsje') }}：</span>
              <span class="message-value-style">{{ cardMessage.remainingGiveMoney?cardMessage.remainingGiveMoney:0 }}</span>
              <!-- <span class="message-title-style">{{ $t('message.ye') }}：</span>
              <span class="message-value-style">{{ cardMessage.money }}</span> -->
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChangeAdmin">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmBtn">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.glty')"
      :visible.sync="isShowManaMem"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      width="1000px"
    >
      <div>
        <QueryForm
          v-model="filtersManager"
          :query-form-config="managerFormConfig"
          @handleQuery="getTeamGroupList(1)"
          @clear="clear2"
        />
        <div v-if="meta.indexOf('AddTeamMember') > -1" class="mb20">
          <el-button type="primary" @click="openTeamMem">{{ $t('message.tjty') }}</el-button>
        </div>
        <el-table
          ref="table"
          :data="managetList"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
        >
          <el-table-column
            align="center"
            :label="$t('message.tyxx')"
            min-width="160"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.touxian')"
            min-width="80"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-image v-if="scope.row.showAvatar" :preview-src-list="[scope.row.showAvatar]" style="width: 40px" :src="scope.row.showAvatar" alt="" />
              <img v-else style="width: 40px" src="@/assets/images/default_space.png">
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('message.hykdj')"
            min-width="120"
            prop="cardType"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.zzje')"
            min-width="100"
            prop="transferAmot"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.tjsj')"
            min-width="160"
            prop="creatTime"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.caozuo')"
            min-width="160"
            prop="teamInfo"
            show-overflow-tooltip
          >
            <template v-slot="scope">
              <div v-if="scope.row.type != '1'" class="flex-cc">
                <el-button
                  v-if="meta.indexOf('TransferAccount') > -1"
                  v-preventReClick
                  type="text"
                  @click="transform(scope.row)"
                >{{ $t('message.zhuanzhan') }}</el-button>
                <el-button
                  v-if="meta.indexOf('DeleteTeamMember') > -1"
                  v-preventReClick
                  type="text"
                  class="red"
                  @click="rowDelete(scope.row)"
                >{{ $t('message.del') }}</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Paginations
          :total="teamTotal"
          :page="teamPagination.page"
          @current-change="getTeamGroupList"
          @SizeChange="handleSizeChangeTeam"
        />
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.tjty')"
      :visible.sync="isShowTeamMem"
      width="400px"
    >
      <el-input v-model="teamMemPhone" oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0,11)" :placeholder="$t('message.qsr') + $t('message.tysjh')" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowTeamMem = false">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmTeamMem">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('message.zhuanzhan')"
      :visible.sync="isShowTransfer"
      width="500px"
    >
      <el-input v-model="tramPeoParam.money" oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" class="mb20" :placeholder="$t('message.qsrzhjezd2')" />
      <el-input v-model="tramPeoParam.payPw" type="password" show-password :placeholder="$t('message.qsr') + $t('message.zfmm')" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowTransfer = false">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmTransfer">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
    <Detail v-if="isShowDetail" ref="detailRef" />
  </div>
</template>

<script>
import {
  listTeam,
  VIPInfo,
  memberTeamDelete,
  changTeamAdmin,
  teamGroupListPost,
  teamGroupAddPost,
  teamGroupDelPost,
  teamGroupTransferPost
} from '@/api'
import { parseTime } from '@/utils/index'
import QueryForm from '@/components/QueryForm'
import Detail from '../../groupDetails'
import store from '@/store'
import { queryFormConfig } from './config'
export default {
  components: {
    QueryForm,
    Detail
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      isShowManaMem: false,
      isShowDetail: false,
      filtersManager: {},
      tramPeoParam: {

      },
      activeTeamId: '',
      teamPagination: {
        page: 1,
        rows: 10
      },
      isShowTeamMem: false,
      isShowTransfer: false,
      teamMemPhone: '',
      managetList: [],
      teamTotal: 0,
      queryFormConfig,
      list: [],
      listLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      cardNum: '',
      cardMessage: {},
      showMessage: false,
      venueId: sessionStorage.getItem('venueId'),
      filters: {},
      showDetails: false,
      form: {},
      managerFormConfig: {
        formItems: [{
          filed: 'memberInfo',
          type: 'input',
          label: this.$t('message.tyxx')
        }, {
          filed: 'createDate',
          type: 'date',
          label: this.$t('message.tjsj')
        }],
        online: true
      }
    }
  },
  created() {
    this.getList(1)
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    openTeamMem() {
      this.teamMemPhone = ''
      this.isShowTeamMem = true
    },
    confirmTeamMem() {
      const { teamMemPhone, activeTeamId } = this
      if (!teamMemPhone) {
        return this.$message.warning(this.$t('message.qxsrtysjh'))
      }
      teamGroupAddPost({
        param: {
          teamId: activeTeamId,
          venueId: sessionStorage.getItem('venueId'),
          phone: teamMemPhone
        }
      }).then(res => {
        if (res.errorCode !== '000000') return
        this.$message.success(this.$t('message.tytjcg'))
        this.getTeamGroupList()
        this.isShowTeamMem = false
      })
    },
    confirmTransfer() {
      const { tramPeoParam, activeTeamId } = this
      teamGroupTransferPost({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          teamId: activeTeamId,
          payPw: tramPeoParam.payPw,
          money: tramPeoParam.money,
          inCardNo: tramPeoParam.inCardNo
        },
        channel: '02'
      }).then(res => {
        if (res.errorCode !== '000000') return
        this.$message.success(this.$t('message.zhcg'))
        this.getTeamGroupList()
        this.isShowTransfer = false
      })
    },
    transform(row) {
      this.isShowTransfer = true
      this.tramPeoParam = {
        inCardNo: row.cardNo
      }
    },
    rowDelete(row) {
      this.$confirm(this.$t('message.sctytc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      }).then(res => {
        const { activeTeamId } = this
        teamGroupDelPost({
          param: {
            teamId: activeTeamId,
            venueId: sessionStorage.getItem('venueId'),
            memberId: [row.memberId]
          }
        }).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.delcg'))
          this.getTeamGroupList()
        })
      })
    },
    ShowManaMem(row) {
      this.isShowManaMem = true
      this.activeTeamId = row.teamId
      this.getTeamGroupList()
    },
    getTeamGroupList(page) {
      if (page) {
        this.teamPagination.page = page
      }
      teamGroupListPost({ param: { teamId: this.activeTeamId, ...this.filtersManager }, pagination: this.teamPagination }).then(res => {
        this.managetList = res.recordList || []
        this.teamTotal = res.totalCount || 0
      })
    },
    memberOpen() {
      this.$router.push({ name: 'GroupOpen' })
    },
    closeMessage() {
      this.showMessage = false
      this.cardMessage = {}
      this.cardNum = ''
      this.form.id = ''
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleSizeChangeTeam(value) {
      this.teamPagination.rows = value
      this.getTeamGroupList()
    },
    searchAction() {
      // console.log('搜索会员卡')
      if (!this.cardNum.length) {
        this.$message.error(this.$t('message.qsr') + this.$t('message.hy1'))
        return
      }
      VIPInfo({
        param: {
          phoneOrNo: this.cardNum
        }
      })
        .then(res => {
          // console.log(res)
          if (res.errorCode === '000000') {
            this.cardMessage = res.record
            this.showMessage = true
            this.form.id = this.cardMessage.id
          }
        })
        .catch(err => {
          console.log(err)
          this.cardMessage = {}
          this.showMessage = false
        })
    },
    // 获取团体列表
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      listTeam({
        param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        },
        pagination,
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // {{ $t('message.ttxq') }}
    groupDetail(id) {
      this.isShowDetail = true
      this.$nextTick(() => {
        this.$refs.detailRef.isShowModal = true
        this.$refs.detailRef.teamId = id
        this.$refs.detailRef.getDetail(id)
        this.$refs.detailRef.getTeamMemberList()
      })
      // this.$router.push({ name: 'GroupDetails', query: { id: id }})
    },
    // 编辑团体
    editGroup(id) {
      this.$router.push({ name: 'GroupEdit', query: { id: id, isRenew: false }})
    },
    // 续签
    reNew(id) {
      this.$router.push({ name: 'GroupEdit', query: { id: id, isRenew: true }})
    },
    // 撤销团体
    backOut(teamId) {
      const that = this
      this.$confirm(this.$t('message.cxtttc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          memberTeamDelete({ param: { teamId }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.cxcg'))
              that.getList()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    // 取消更换管理员
    cancelChangeAdmin() {
      this.showDetails = false
      this.cardMessage = {}
      this.cardNum = ''
      this.showMessage = false
    },
    // 确认更换管理员
    confirmBtn() {
      if (!this.cardMessage.id) {
        this.$message.warning(this.$t('message.qsrkhsjhss'))
        return
      }
      changTeamAdmin({ param: {
        id: this.form.teamId,
        adminId: this.cardMessage.id,
        venueId: sessionStorage.getItem('venueId')
      }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.showDetails = false
        this.$message.success(this.$t('message.ghcg2'))
        this.getList()
      }).catch(() => {
      })
    },
    changeAdmintor(item) {
      this.$confirm(this.$t('message.ghglytc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          this.showMessage = false
          this.cardNum = ''
          this.showDetails = true
          item = JSON.stringify(item)
          item = JSON.parse(item)
          this.form = item
          this.cardMessage = {}
        })
        .catch(() => {
          // this.$message.info('已取消操作')
        })
    },
    clear() {
      this.filters = {}
      this.getList(1)
    },
    clear2() {
      this.filtersManager = {}
      this.getTeamGroupList()
    }
  }
}
</script>
<style lang="scss" scoped>
.card-message {
  margin-top: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
</style>
